package com.atguigu.tingshu;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.vo.base.user.UserInfo;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Random;

@SpringBootTest
public class Init {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Resource
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Resource
    private UserInfoFeignClient userInfoFeignClient;
    @Resource
    private CategoryFeignClient categoryFeignClient;

    @Test
    public void creatIndex() {
        //索引库
        IndexOperations indexOps = elasticsearchTemplate.indexOps(AlbumInfoIndex.class);
        if (!indexOps.exists()) {
            indexOps.create();
            indexOps.putMapping();
        }
        //提示词库
        IndexOperations operations = elasticsearchTemplate.indexOps(SuggestIndex.class);
        if (!operations.exists()) {
            operations.create();
            operations.putMapping();
        }
    }

    @Test
    public void initData() {
        //1、按页查询专辑的基本信息
        Integer pageNum = 1;
        Integer pageSize = 100;
        do {
            Result<List<AlbumListVo>> allAlbumPageR = albumInfoFeignClient.findAllAlbumPage(pageNum, pageSize);
            Assert.notNull(allAlbumPageR, "数据导入时，获取专辑信息失败！");
            List<AlbumListVo> albumListVos = allAlbumPageR.getData();
            if (!CollectionUtils.isEmpty(albumListVos)) {
                albumListVos.forEach(albumListVo -> {
                    AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
                    BeanUtils.copyProperties(albumListVo, albumInfoIndex);
                    albumInfoIndex.setId(albumListVo.getAlbumId());
                    //2、根据userId查询用户信息
                    Result<UserInfo> userInfoR = userInfoFeignClient.getUserInfo(albumListVo.getUserId());
                    Assert.notNull(userInfoR, "数据导入时，获取用户信息失败！");
                    UserInfo userInfo = userInfoR.getData();
                    if (userInfo != null) {
                        albumInfoIndex.setAnnouncerName(userInfo.getNickname());
                    }
                    //3、根据第三级分类id获取三级id
                    Result<BaseCategoryView> baseCategoryViewR = categoryFeignClient.findBaseCategoryView(albumListVo.getCategory3Id());
                    Assert.notNull(baseCategoryViewR, "数据导入时，获取三级分类数据信息失败！");
                    BaseCategoryView categoryView = baseCategoryViewR.getData();
                    if (categoryView != null) {
                        albumInfoIndex.setCategory1Id(categoryView.getCategory1Id());
                        albumInfoIndex.setCategory2Id(categoryView.getCategory2Id());
                    }
                    albumInfoIndex.setPlayStatNum((new Random().nextInt(10) + 1) * 10000000);
                    albumInfoIndex.setSubscribeStatNum((new Random().nextInt(10) + 1) * 10000000);
                    albumInfoIndex.setBuyStatNum((new Random().nextInt(10) + 1) * 10000000);
                    albumInfoIndex.setCommentStatNum((new Random().nextInt(10) + 1) * 10000000);
                    albumInfoIndex.setHotScore(albumInfoIndex.getPlayStatNum() * 0.1 + albumInfoIndex.getCommentStatNum() * 0.2 + albumInfoIndex.getCommentStatNum() * 0.3 + albumInfoIndex.getBuyStatNum() * 0.4);
                    //4、根据专辑id获取专辑属性值列表
                    Result<AlbumInfo> albumInfoR = albumInfoFeignClient.getAlbumInfo(albumListVo.getAlbumId());
                    Assert.notNull(albumInfoR, "数据导入时，获取专辑失败！");
                    albumInfoIndex.setAttributeValueIndexList(albumInfoR.getData().getAlbumAttributeValueVoList().stream().map(albumAttributeValue -> {
                        AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                        BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                        return attributeValueIndex;
                    }).toList());
                    elasticsearchTemplate.save(albumInfoIndex);
                    ///5、保存专辑标题的搜索建议
                    //5.1、标题匹配
                    SuggestIndex titleSuggestIndex = new SuggestIndex();
                    titleSuggestIndex.setId("title" + albumInfoIndex.getId().toString());
                    titleSuggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
                    titleSuggestIndex.setKeyword(new Completion(Collections.singletonList(albumInfoIndex.getAlbumTitle())));
                    titleSuggestIndex.setKeywordPinyin(new Completion(Collections.singletonList(PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle()))));
                    titleSuggestIndex.setKeywordSequence(new Completion(Collections.singletonList(PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle()))));
                    elasticsearchTemplate.save(titleSuggestIndex);
                    //5.2、简介匹配
                    SuggestIndex introSuggestIndex = new SuggestIndex();
                    introSuggestIndex.setId("intro" + albumInfoIndex.getId().toString());
                    introSuggestIndex.setTitle(albumInfoIndex.getAlbumIntro());
                    introSuggestIndex.setKeyword(new Completion(Collections.singletonList(albumInfoIndex.getAlbumIntro())));
                    introSuggestIndex.setKeywordPinyin(new Completion(Collections.singletonList(PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumIntro()))));
                    introSuggestIndex.setKeywordSequence(new Completion(Collections.singletonList(PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumIntro()))));
                    elasticsearchTemplate.save(introSuggestIndex);
                    //5.3、主播名匹配
                    if (albumInfoIndex.getAnnouncerName() != null) {
                        SuggestIndex announcerNameSuggestIndex = new SuggestIndex();
                        announcerNameSuggestIndex.setId("announcerName" + albumInfoIndex.getId().toString());
                        announcerNameSuggestIndex.setTitle(albumInfoIndex.getAnnouncerName());
                        announcerNameSuggestIndex.setKeyword(new Completion(Collections.singletonList(albumInfoIndex.getAnnouncerName())));
                        announcerNameSuggestIndex.setKeywordPinyin(new Completion(Collections.singletonList(PinYinUtils.toHanyuPinyin(albumInfoIndex.getAnnouncerName()))));
                        announcerNameSuggestIndex.setKeywordSequence(new Completion(Collections.singletonList(PinYinUtils.getFirstLetter(albumInfoIndex.getAnnouncerName()))));
                        elasticsearchTemplate.save(announcerNameSuggestIndex);
                    }
                });
            }
            pageNum++;
            pageSize = albumListVos.size();
        } while (pageSize == 100);
    }
}

